<template>
  <div class="wrapper">
    <div class="item-detail-show">
      <!-- 详情左侧展示数据、图片，收藏、举报 -->
      <div class="item-detail-left">
        <!-- 大图、放大镜、视频 -->
        <magnifyingGlass :images="imgList" :video="skuDetail.goodsVideo"></magnifyingGlass>
        <div v-if="skuDetail.goodsType !== 'VIRTUAL_GOODS'" style="margin-top:10px;color: #666666;">实物商品</div>
        <div v-else-if="skuDetail.goodsType == 'VIRTUAL_GOODS'" style="margin-top:10px;color: #666666;">虚拟商品</div>
        <div class="goodsConfig mt_10">
          <span @click="collect">
            <template v-if="isCollected">
                <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24">
                  <path fill="#ef4444" d="M12.001 4.529a5.998 5.998 0 0 1 8.242.228a6 6 0 0 1 .236 8.236l-8.48 8.492l-8.478-8.492a6 6 0 0 1 8.48-8.464"/>
                </svg>
                已收藏
              </template>
              <template v-else>
                <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24">
                  <path fill="#999999" d="M12.001 4.529a5.998 5.998 0 0 1 8.242.228a6 6 0 0 1 .236 8.236l-8.48 8.492l-8.478-8.492a6 6 0 0 1 8.48-8.464m6.826 1.641a3.998 3.998 0 0 0-5.49-.153l-1.335 1.198l-1.336-1.197a4 4 0 0 0-5.686 5.605L12 18.654l7.02-7.03a4 4 0 0 0-.193-5.454"/>
                </svg>
                收藏
              </template>
          </span>
        </div>
      </div>
      <!-- 右侧商品信息、活动信息、操作展示 -->
      <div class="item-detail-right">
        <div class="item-detail-title text-color"><p>{{ skuDetail.goodsName }}</p></div>
        <div class="sell-point">{{ skuDetail.sellingPoint }}</div>
        <!--限时秒杀占位-->
        <div>
          <Promotion v-if="promotionMap['SECKILL']" :time="promotionMap['SECKILL'].endTime"></Promotion>
        </div>
        <!-- 商品详细 价格、优惠券、促销 -->
        <div class="item-detail-price-row">
          <div class="item-price-left">
            <!-- 秒杀价格 -->
            <div class="item-price-row" style="height: 30px;" v-if="skuDetail.promotionPrice && promotionMap['SECKILL']">
              <p>
                <span class="item-price-title" v-if="promotionMap['SECKILL']">秒 &nbsp;杀&nbsp;价</span>
                <span class="item-price">{{unitPrice(skuDetail.promotionPrice, "￥")}}</span>
                <span class="item-price-old">{{unitPrice(skuDetail.price, "￥")}}</span>
              </p>
            </div>
            <!-- 商品原价 -->
            <div class="item-price-row" v-else>
              <!-- 批发价格 -->
              <div v-if="wholesaleNum && wholesaleNum.length" style="line-height: 32px;">
                <div class="flex">
                  <div class="item-price-title">价 &nbsp;&nbsp;&nbsp;&nbsp;格</div>
                  <div v-for="(item, index) in wholesalePrice" :key="index" class="item-price item-num">{{ unitPrice(item, "￥") }}</div>
                </div>
                <div class="flex">
                  <div class="item-price-title">起 批 量</div>
                  <div v-for="(item, index) in wholesaleNum" :key="index" class="item-num item-price-num">{{ item }}{{ skuDetail.goodsUnit }}</div>
                </div>
              </div>
              <!-- 普通价格 -->
              <template v-else>
                <span class="item-price-title">价 &nbsp;&nbsp;&nbsp;&nbsp;格</span>
                <span class="item-price">{{unitPrice(skuDetail.price, "￥")}}</span>
              </template>
            </div>
            <!-- 优惠券展示 -->
            <div class="item-price-coupon-row" v-if="promotionMap['COUPON'].length">
              <div class="Ellipsis">
                <span class="item-price-title">优 惠 券</span>
                <!--<span>-->
                  <span class="item-coupon" v-for="(item, index) in promotionMap['COUPON'].slice(0, 6)" :key="index" @click="handleReceiveCoupon(item.id)">
                    <span v-if="item.couponType == 'PRICE'">满{{ item.consumeThreshold }}减{{ item.price }}</span>
                    <span v-if="item.couponType == 'DISCOUNT'">满{{ item.consumeThreshold }}打{{item.couponDiscount}}折</span>
                  </span>
                <!--</span>-->
                <div class="dropdown" v-if="promotionMap['COUPON'].length > 6">
                  <span>展开更多</span>
                  <div class="dropdown-content">
                    <span class="item-coupon" v-for="(item, index) in promotionMap['COUPON'].slice(6, promotionMap['COUPON'].length)" :key="index" @click="handleReceiveCoupon(item.id)">
                      <span v-if="item.couponType == 'PRICE'">满{{ item.consumeThreshold }}减{{ item.price }}</span>
                      <span v-if="item.couponType == 'DISCOUNT'">满{{ item.consumeThreshold }}打{{item.couponDiscount}}折</span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <!-- 满减展示 -->
            <div class="item-price-row" v-if="promotionMap['FULL_DISCOUNT']">
              <!--<p>-->
                <span class="item-price-title">促&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;销</span>
                <span class="item-promotion">满减</span>
                <span class="item-desc-pintuan" v-if="promotionMap['FULL_DISCOUNT'].fullMinus">
                  满{{ promotionMap["FULL_DISCOUNT"].fullMoney }}元，立减现金{{promotionMap["FULL_DISCOUNT"].fullMinus}}元
                </span>
                <span class="item-desc-pintuan" v-if="promotionMap['FULL_DISCOUNT'].fullRate &&promotionMap['FULL_DISCOUNT'].fullRateFlag">
                  满{{ promotionMap["FULL_DISCOUNT"].fullMoney }}元，立享{{promotionMap["FULL_DISCOUNT"].fullRat}}折
                </span>
              <!--</p>-->
            </div>
          </div>
          <div class="item-price-right">
            <div class="item-remarks-sum">
              <p>累计评价</p>
              <p><span class="item-remarks-num">{{ skuDetail.commentNum || 0 }} 条</span>
              </p>
            </div>
          </div>
        </div>
        <!-- 选择颜色 -->
        <div class="item-select" v-for="(sku, index) in formatList" :key="sku.name">
          <div class="item-select-title">{{ sku.name }}</div>
          <div class="item-select-column">
            <div class="item-select-row" v-for="item in sku.values" :key="item.value">
              <div class="item-select-box" @click="select(index, item.value)" :class="{'item-select-box-active': item.value === currentSelceted[index]}">
                <div class="item-select-intro"><p>{{ item.value }}</p></div>
              </div>
            </div>
          </div>
        </div>
        <br />
        <div class="add-buy-car-box">
          <div class="item-select mb_20">
            <div class="item-select-title">数量</div>
            <div class="item-select-row">
              <a-input-number v-model="count" :style="{width:'100px'}" :disabled="skuDetail.quantity === 0" :min="1" :max="skuDetail.quantity" @blur="changeCount"/>
              <span class="inventory text-color"> 库存{{ skuDetail.quantity }}</span>
            </div>
          </div>
          <div class="item-select mb_20" v-if="skuDetail.goodsType !== 'VIRTUAL_GOODS' && skuDetail.weight !== 0">
            <div class="item-select-title">重量</div>
            <div class="item-select-row"><span class="inventory"> {{ skuDetail.weight }}kg</span></div>
          </div>
          <div class="add-buy-car mt_20" v-if="route.query.way === 'POINT' && skuDetail.authFlag === 'PASS'">
            <a-button type="primary" status="danger" :loading="loading" :disabled="skuDetail.quantity === 0" @click="pointPay">积分购买</a-button>
          </div>
          <div class="add-buy-car mt_20" v-if="route.query.way !== 'POINT' && skuDetail.authFlag === 'PASS'">
            <a-button type="primary" status="danger" class="mr_10"
                      :loading="loading" v-if="skuDetail.goodsType !== 'VIRTUAL_GOODS'" :disabled="skuDetail.quantity === 0" @click="addShoppingCartBtn">加入购物车</a-button>
            <a-button type="primary" status="warning" :loading="loading1" :disabled="skuDetail.quantity === 0" @click="buyNow">立即购买</a-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted, computed } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { unitPrice } from '@/utils/filters';
  import storage from '@/utils/storage';
  import { useRouter, useRoute } from 'vue-router';
  import { collectGoods, isCollection, receiveCoupon, cancelCollect } from "@/api/member";
  import { addCartGoods } from "@/api/cart";

  const route = useRoute();
  const router = useRouter();
  /**
   * 接收父组件传值
   */
  const props = defineProps({
    // 商品数据
    detail: {
      type: Object,
      default: () => {return {}}
    },
  });

  const wholesaleList = ref<any>([]);
  const count = ref(1); // 商品数量
  const currentSelceted = ref<any>([]); // 当前商品sku
  const imgList = ref<Array<any>>([]); // 当前商品图片列表
  // sku详情
  const skuDetail = ref<any>({specList: []});
  const goodsSpecList = ref(props.detail.specs); // 商品spec
  // 促销活动
  const promotionMap = ref<any>({
    // 活动状态
    SECKILL: null,
    FULL_DISCOUNT: null,
    COUPON: [],
  });
  const formatList = ref<any>([]); //选择商品品类的数组
  const loading = ref(false); // 立即购买loading
  const loading1 = ref(false); // 加入购物车loading
  const isCollected = ref(false); // 是否收藏
  const skuList = ref([]);
  const wholesalePrice = computed(() => {
    return wholesaleList.value&&wholesaleList.value.length?wholesaleList.value.map((item: any) => {
      return item.price;
    }):[];
  });
  const wholesaleNum = computed(() => {
    return wholesaleList.value&&wholesaleList.value.length?wholesaleList.value.map((item: any) => {
      return item.num;
    }):[];
  });

  const emit = defineEmits(['handleClickSku']);

  // 格式化数据
  const formatSku = (list: any) => {
    let arr = [{}];
    list.forEach((item: any, index : any) => {
      item.specValues.forEach((spec: any, specIndex: any) => {
        let name = spec.specName;
        let values = {value: spec.specValue, quantity: item.quantity,};
        if (name === "images") {return;}
        arr.forEach((arrItem: any) => {
          if (arrItem.name === name && arrItem.values && !arrItem.values.find((i: any) => i.value === values.value)) {arrItem.values.push(values);}
          let keys = arr.map((key: any) => {return key.name;});
          if (!keys.includes(name)) {
            arr.push({name: name, values: [values],});
          }
        });
      });
    });
    arr.shift();
    formatList.value = arr;
    let cur = list.filter((i: any) => i.skuId === route.query.skuId)[0];
    if (cur) {
      cur.specValues.filter((i: any) => i.specName !== "images").forEach((value: any, _index: any) => {
        currentSelceted.value[_index] = value.specValue;
      });
    }
    skuList.value = list;
  };
  // 格式化促销活动，返回当前促销的对象
  const promotion = () => {
    if (!props.detail.promotionMap) return false;
    let keysArr = Object.keys(props.detail.promotionMap);
    if (keysArr.length === 0) return false;
    for (const element of keysArr) {
      let key = element.split("-")[0];
      if (key === "COUPON") {
        promotionMap.value[key].push(props.detail.promotionMap[element]);
      } else {
        promotionMap.value[key] = props.detail.promotionMap[element];
      }
    }
  };
  // 商品图片
  const swiperGoodsImg = () => {
    skuDetail.value.specList.forEach((e: any) => {
      if (e.specName === "images") {
        imgList.value = skuDetail.value.goodsGalleryList.filter((i: any) => i.indexOf("\"url\":") === -1 && i.indexOf("\"status\":") === -1);
      }
    });
    if (!imgList.value) {
      imgList.value = [skuDetail.value.original];
    }
  };
  // 收藏商品
  const collect = async () => {
    if (isCollected.value) {
      let cancel = await cancelCollect("GOODS", skuDetail.value.id);
      if (cancel.data.success) {
        Message.success("取消收藏成功");
        isCollected.value = false;
      }
    } else {
      let collect = await collectGoods("GOODS", skuDetail.value.id);
      if (collect.data.code === 200) {
        Message.success("收藏商品成功,可以前往个人中心我的收藏查看");
        isCollected.value = true;
      }
    }
  };
  // 数量
  const changeCount = (val: any) => {
    if (wholesaleList.value && wholesaleList.value.length > 0) {
      if (count.value <= wholesaleList.value[0].num) {
        Message.warning("批发商品购买数量不能小于起批数量");
        count.value = wholesaleList.value[0].num;
      }
    }
  };
  // 选择规格
  const select = (index: any, value: any) => {
    currentSelceted.value[index] = value;
    let selectedSkuId = goodsSpecList.value.find((i: any) => {
      let matched = true;
      let specValues = i.specValues.filter((j: any) => j.specName !== "images");
      for (let n = 0; n < specValues.length; n++) {
        if (specValues[n].specValue !== currentSelceted.value[n]) {
          matched = false;
          return;
        }
      }
      if (matched) {return i;}
    });
    emit('handleClickSku', {skuId: selectedSkuId.skuId, goodsId: skuDetail.value.goodsId,})
  };
  // 添加购物车
  const addShoppingCartBtn = () => {
    const params = { num: count.value, skuId: skuDetail.value.id };
    loading.value = true;
    addCartGoods(params).then((res) => {
        loading.value = false;
        if (res.data.success) {
          const {id, goodsId, thumbnail, goodsName} = skuDetail.value;
          router.push({path: "/shoppingCart", query: { id, goodsId, thumbnail, goodsName, count: count.value },});
        } else {
          Message.warning(res.data.message);
        }
      }).catch(() => {loading.value = false;});
  };
  // 立即购买
  const buyNow = () => {
    const params = { num: count.value, skuId: skuDetail.value.id, cartType: "BUY_NOW",};
    // 虚拟商品购买
    if (skuDetail.value.goodsType === "VIRTUAL_GOODS") {
      params.cartType = "VIRTUAL";
    }
    loading1.value = true;
    addCartGoods(params).then((res) => {
        loading1.value = false;
        if (res.data.success) {
          router.push({path: "/payment/pay", query: { way: params.cartType },});
        } else {
          Message.warning(res.data.message);
          }
      }).catch(() => {
        loading1.value = false;
      });
  };

  // 领取优惠券
  const handleReceiveCoupon = (id: any) => {
    receiveCoupon(id).then((res) => {
      if (res.data.success) {
        Message.success("优惠券领取成功");
      } else {
        Message.warning(res.data.message);
      }
    });
  };

  // 积分购买
  const pointPay = () => {



  };

  onMounted(() => {
    // 用户登录才会判断是否收藏
    if (storage.getUserInfo()) {
      isCollection("GOODS", skuDetail.value.id).then((res) => {
        if (res.data.success && res.data.result) {
          isCollected.value = true;
        }
      });
    }
    formatSku(goodsSpecList.value);
    promotion();
    document.title = skuDetail.value.goodsName;
  });

  watch(() => props.detail, (val) => {
      skuDetail.value = val.data;
      wholesaleList.value = val.wholesaleList;
      if (wholesaleList.value && wholesaleList.value.length > 0) {
        count.value = wholesaleList.value[0].num;
      }
      swiperGoodsImg();
    }, { immediate: true, deep: true }
  );
</script>

<style scoped lang="less">
  .wrapper {
    @include @light_background_color;
    .item-detail-show {
      width: 1200px;
      margin: 0 auto;
      padding: 30px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      flex-direction: row;
    }
    /*详情左侧展示数据、图片，收藏、举报*/
    .item-detail-left {
      width: 350px;
      position: relative;
      .item-detail-big-img {
        width: 350px;
        height: 350px;
        box-shadow: 0px 0px 8px @border_color;
        cursor: pointer;
      }
      .item-detail-big-img img {
        width: 100%;
      }
      .item-detail-img-row {
        margin-top: 10px;
        display: flex;
      }
      .item-detail-img-small {
        width: 68px;
        height: 68px;
        box-shadow: 0px 0px 8px #ccc;
        cursor: pointer;
        margin-left: 5px;
      }
      .item-detail-img-small img {
        height: 100%;
        width: 100%;
      }
      .goodsConfig {
        display: flex;
        justify-content: space-between;
        > span {
          padding-right: 10px;
          display: flex;
          align-items: center;
          &:hover {
            cursor: pointer;
            color: @theme_color;
          }
        }
      }
    }
    /*商品选购详情*/
    .item-detail-right {
      width: 760px;
      display: flex;
      flex-direction: column;
      .item-detail-title p {
        font-weight: bold;
        font-size: 20px;
        line-height: 46px;
        margin: 0;
      }
      .sell-point {
        font-size: 12px;
        color: @theme_color;
        margin-bottom: 5px;
      }
      /*价格详情等*/
      .item-detail-price-row {
        width: 100%;
        min-height: 60px;
        box-sizing: border-box;
        padding: 10px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        background: url("/src/assets/images/goodsDetail/price-bg.png");
        .item-price-left {
          display: flex;
          flex-direction: column;
        }
        .item-price-title {
          color: #999999;
          font-size: 14px;
          margin-right: 15px;
        }
        .item-price-row {
          margin: 4px 0px;
          display: flex;
          align-items: center;
        }
        .item-price {
          color: @theme_color;
          font-size: 20px;
          cursor: pointer;
        }
        .item-price-old {
          color: gray;
          text-decoration: line-through;
          font-size: 14px;
          margin-left: 5px;
        }
        .item-price-coupon-row {
          display: flex;
          align-items: center;
          margin: 5px 0px;
        }
        .Ellipsis {
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 2; //控制显示几行
          -webkit-box-orient: vertical; //webbox方向
        }
        .dropdown {
          position: relative;
          display: inline-block;
          cursor: pointer;
          z-index: 999;
        }
        .dropdown .item-coupon {
          display: flex;
          align-content: center;
          align-items: center;
          color: @theme_color;
          margin: 5px 0;
          font-size: 12px;
          background-color: #ffdedf;
          border: 1px dotted @theme_color;
          cursor: pointer;
          span {
            padding: 3px;
          }
        }
        .dropdown-content {
          display: none;
          position: absolute;
          background-color: #f9f9f9;
          min-width: 160px;
          box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
          padding: 12px 16px;
        }
        .dropdown:hover .dropdown-content {
          display: block;
        }
        .item-coupon {
          margin-right: 5px;
          padding: 0 5px;
          color: @theme_color;
          font-size: 12px;
          background-color: #ffdedf;
          border: 1px dotted @theme_color;
          cursor: pointer;
          line-height: 16px;
          display: inline-block;
          span {
            padding: 3px;
          }
        }
        .item-promotion {
          margin-right: 5px;
          padding: 2px 3px;
          color: @theme_color;
          font-size: 12px;
          line-height: 12px;
          border: 1px solid @theme_color;
        }
        .item-price-right {
          display: flex;
          align-content: center;
          align-items: center;
        }
        .item-remarks-sum {
          width: 70px;
          height: 40px;
          text-align: center;
          padding: 0 10px;
          border-left: 1px solid @border_color;
          display: flex;
          flex-direction: column;
          justify-content: center;
          p {
            color: #999999;
            font-size: 12px;
            line-height: 20px;
            text-align: center;
            margin: 0;
          }
        }
        .item-remarks-num {
          line-height: 18px;
          color: #005eb7;
        }
      }









    }
    /*选择颜色*/
    .item-select {
      display: flex;
      align-items: center;
      flex-direction: row;
      margin-top: 15px;
      .item-select-title {
        color: @light_content_color;
        font-size: 14px;
        margin-right: 15px;
        width: 60px;
      }
      .item-select-column {
        display: flex;
        flex-wrap: wrap;
        flex: 1;
      }
      .item-select-row {
        /*margin-bottom: 8px;*/
      }
      .item-select-box {
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 3px 5px;
        margin-right: 8px;
        background-color: @light_background_color;
        transition: 0.35s;
        border: 0.5px solid @border_color;
        cursor: pointer;
        color: @light_content_color;
      }
      .item-select-box:hover {
        border: 0.5px solid @theme_color;
      }

      .item-select-box-active {
        border: 0.5px solid @theme_color;
      }

      .item-select-intro p {
        margin: 0px;
        padding: 5px;
      }


    }
    /*选择数量 加入购物车 立即购买*/
    .add-buy-car-box {
      width: 100%;
      margin-top: 15px;
      border-top: 1px dotted @border_color;
    }
  }


  .item-num {
    text-align: center;
    width: 100px;
  }
  .item-price-num {
    font-size: 16px;
    color: #666;
  }
</style>
